import { getList as getChannelOrders } from '@/api/order';
import { getProjectChildOrder, getList as getProjectOrders } from '@/api/project';
const ORDER_TYPE = {
  CHANNEL: 1, // 渠道订单
  PROJECT_CHANNEL: 4, // 项目渠道订单
  PROJECT: 2 // 项目订单
};
export default {
  watch: {
    orders: {
      handler(data) {
        // 设置抽屉已选中的列表项
        data && this.formatOrderToTable(data);
      },
      deep: true
    }
  },
  methods: {
    // 删除deletedList中与list相同的数据
    mulRowsDel(list, deletedList) {
      if (!Array.isArray(list) || !list.length) return deletedList;
      const deepCloneList = _.cloneDeep(list);
      let curRow;
      // eslint-disable-next-line no-cond-assign
      while (curRow = deepCloneList.pop()) {
        for (let index = deletedList.length - 1; index >= 0; index--) {
          if (deletedList[index].relatedId && deletedList[index].relatedId === curRow.relatedId && deletedList[index].orderType === curRow.orderType) {
            deletedList.splice(index, 1);
          }
        }
      }
      return deletedList;
    },
    formatOrders(list, type) {
      const isNewList = list.filter(item => item.id && !item.relatedId && !item.customizeState);
      // orders中相同type的数组
      const sameTypeList = this.orders.filter(item => item.orderType === type);
      if (sameTypeList.length) {
        // orders中删除第二次抽屉没有选中的同类型的数据
        const diffSelectedList = list.filter(item => item.relatedId);
        const ExcessList = this.mulRowsDel(diffSelectedList, sameTypeList);
        this.orders = this.mulRowsDel(ExcessList, this.orders);
      }
      // 返回orders第一次没有选中过的值
      return isNewList;
    },
    setOrders(data) {
      Object.keys(data).forEach(tableName => {
        let list = [];
        switch (tableName) {
          case 'channelTable':
            list = this.formatOrders(data[tableName], ORDER_TYPE.CHANNEL);
            this.orders.push(...this.formatOrderTable(list, ORDER_TYPE.CHANNEL));
            this.refreshOrderOldData(data[tableName], ORDER_TYPE.CHANNEL);
            break;
          case 'projectChannelTable':
            list = this.formatOrders(data[tableName], ORDER_TYPE.PROJECT_CHANNEL);
            this.orders.push(...this.formatOrderTable(list, ORDER_TYPE.PROJECT_CHANNEL));
            this.refreshOrderOldData(data[tableName], ORDER_TYPE.PROJECT_CHANNEL);
            break;
          case 'projectTable':
            list = this.formatOrders(data[tableName], ORDER_TYPE.PROJECT);
            this.orders.push(...this.formatOrderTable(list, ORDER_TYPE.PROJECT));
            this.refreshOrderOldData(data[tableName], ORDER_TYPE.PROJECT);
            break;
        }
      });
    },
    formatOrderTable(list, type) {
      const result = [];
      switch (type) {
        case ORDER_TYPE.CHANNEL:
        case ORDER_TYPE.PROJECT_CHANNEL:
          list.forEach(item => {
            const { orderInfo } = item;
            const orderItem = this.formatTableToOrder(orderInfo, type);
            orderItem.publishPrice = this.formatPrice(orderInfo.articlesPrice); // 刊例价
            orderItem.contractPrice = this.formatPrice(orderInfo.taxAmount); // 合同金额（含税价格）
            result.push(orderItem);
          });
          break;
        case ORDER_TYPE.PROJECT:
          list.forEach(item => {
            const orderItem = this.formatTableToOrder(item, type);
            orderItem.orderNum = item.projectNum;
            orderItem.exeTheme = item.brandName;
            orderItem.publishPrice = this.formatPrice(item.articlesPrice); // 刊例价
            orderItem.contractPrice = this.formatPrice(item.taxAmount); // 合同金额（含税价格）
            result.push(orderItem);
          });
          break;
      }
      return result;
    },
    // 订单信息新数据替换保存的旧数据
    refreshOrderOldData(list, type) {
      const resetList = list.filter(item => item.relatedId && !item.customizeState);
      if (!resetList.length) return;
      const ids = list.map(item => item.relatedId).join(',');
      switch (type) {
        case ORDER_TYPE.CHANNEL:
          getChannelOrders(1, 9999, { ids }).then(res => {
            this.replaceOldOrders(res.data && res.data.items, type);
          }).catch(_ => {});
          break;
        case ORDER_TYPE.PROJECT_CHANNEL:
          getProjectChildOrder({ page: 1, perPage: 9999, ids }).then(res => {
            this.replaceOldOrders(res.data && res.data.items, type);
          }).catch(_ => {});
          break;
        case ORDER_TYPE.PROJECT:
          getProjectOrders({ page: 1, perPage: 9999, ids }).then(res => {
            this.replaceOldOrders(res.data && res.data.items, type);
          }).catch(_ => {});
          break;
      }
    },
    replaceOldOrders(list, type) {
      if (!Array.isArray(list) || !list.length) return;
      const newOrders = this.formatOrderTable(list, type);
      newOrders.forEach(newOrder => {
        const newOrderIndex = this.orders.findIndex(item => item.relatedId === newOrder.relatedId);
        if (newOrderIndex !== -1) {
          const oldOrder = this.orders[newOrderIndex];
          // 执行类型和内容来源回填
          newOrder.exeType = oldOrder.exeType;
          newOrder.contentSource = oldOrder.contentSource;
          this.orders.splice(newOrderIndex, 1, newOrder);
        }
      });
    },
    // 抽屉数据层级结构转化成订单信息数据结构
    formatTableToOrder(orderRow, type) {
      if (!orderRow) return;
      const formatRuleData = {
        relatedId: 'id',
        orderNum: 'orderId', // 订单编号
        exeTheme: 'theme', // 执行主题（品牌名称）
        exeAccount: 'resourceName', // 执行账号
        orderPlatform: 'orderPlatformId', // 下单平台id
        orderPlatformName: 'orderPlatform', // 下单平台
        exeType: 'exeType', // 执行类型id（1:图文； 2: 视频， 3: 直播； 0: 其他）
        contentSource: 'contentSource' // 内容来源id（1: 客户供稿； 2: 我方撰写）
      };
      const orderItem = Object.create(null);
      for (const key in formatRuleData) {
        orderItem[key] = orderRow[formatRuleData[key]];
      }
      orderItem.orderType = type; // 订单类型id（0: 其他； 1: 渠道订单 ；2:项目订单；3: 萌力渠道订单, 4: 项目渠道订单）
      orderItem.orderTypeName = this.getTypeName(type);
      orderItem.orderPrivateId = ++this.orderPrivateId;
      orderItem.disable = true;
      orderItem.customizeState = false;
      return orderItem;
    },
    getTypeName(type) {
      let result = '';
      switch (type) {
        case ORDER_TYPE.CHANNEL:
          result = '渠道订单';
          break;
        case ORDER_TYPE.PROJECT_CHANNEL:
          result = '项目渠道单';
          break;
        case ORDER_TYPE.PROJECT:
          result = '项目订单';
          break;
        default:
          result = '其他';
          break;
      }
      return result;
    },
    formatPrice(val) {
      if (!val) return;
      return (parseFloat(val) / 100).toFixed(2);
    },
    // 订单信息数据结构转化成抽屉数据层级结构
    formatOrderToTable(data) {
      if (!Array.isArray(data) || !data.length) return;
      const channelTable = data.filter(item => item.orderType === ORDER_TYPE.CHANNEL && !item.customizeState) || [];
      const projectChannelTable = data.filter(item => item.orderType === ORDER_TYPE.PROJECT_CHANNEL && !item.customizeState) || [];
      const projectTable = data.filter(item => item.orderType === ORDER_TYPE.PROJECT && !item.customizeState) || [];
      this.$nextTick(() => {
        this.$refs['relatedOrders'].selectedData = {
          channelTable,
          projectChannelTable,
          projectTable
        };
      });
    }
  }
};
